/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: client.c
> Author: KAIJIE.JIANG
> Mail: 
> Created Time: 2024年08月13日 星期二 10时57分03秒
***************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cJSON.h>

struct calculate{
	char type[10];
	int data1;
	int data2;
};

void setpack(char *buf,struct calculate *cal);
void unpack(char *buf);

int main(int argc,const char* argv[])
{

	int sock = 0;
	int ret = 0;
	char buf[1024] = {0};

	struct sockaddr_in serAddr;
    memset(&serAddr,0,sizeof(serAddr));

	sock = socket(AF_INET,SOCK_STREAM,0);
	if(sock == -1)
	{
		perror("sock");
		exit(-1);
	}

	serAddr.sin_family = AF_INET;
    serAddr.sin_port = htons(6868);
    serAddr.sin_addr.s_addr = htonl(INADDR_ANY);

	ret = connect(sock,(struct sockaddr *)&serAddr,sizeof(struct sockaddr));
	if(ret == -1){
		perror("connect");
		exit(-1);
	}

	printf("model:\nadd\tsub\tmul\tdiv\tquit\n");

	struct calculate cal;

	while(1)
	{

		memset(buf,0,sizeof(char)*1024);
		memset(&cal,0,sizeof(struct calculate));

		printf("please input type:");
		scanf("%s",cal.type);

		if(strcmp(cal.type,"quit") != 0){
			printf("input data1:");
			scanf("%d",&cal.data1);
			printf("input data2:");
			scanf("%d",&cal.data2);
		}

		setpack(buf,&cal);

		ret = send(sock,buf,strlen(buf),0);
		if(ret == -1)
		{
			perror("send");
		}
		
		if(strcmp(cal.type,"quit") == 0){
			break;
		}

		memset(buf,0,sizeof(buf));

		ret = recv(sock,buf,1023,0);
		if(ret == -1){
			perror("recv");
		}

		unpack(buf);

	}

	close(sock);

    return 0;
}

void setpack(char *buf,struct calculate *cal){
	cJSON *json = NULL;
	json = cJSON_CreateObject();

	cJSON_AddItemToObject(json,"type",cJSON_CreateString(cal->type));
	cJSON_AddItemToObject(json,"data1",cJSON_CreateNumber(cal->data1));
	cJSON_AddItemToObject(json,"data2",cJSON_CreateNumber(cal->data2));

	char *dest = cJSON_Print(json);
	strcpy(buf,dest);

	free(dest);
	cJSON_Delete(json);
}

void unpack(char *buf){
	cJSON * json = NULL;
	json = cJSON_Parse(buf);

	cJSON *node = NULL;
	node = cJSON_GetObjectItem(json,"type");
	if(node == NULL){
		printf("error:cJSON_GetObjectItem\n");
		cJSON_Delete(json);
		exit(-1);
	}
	if(node->type == cJSON_String){
		printf("type:%s\n",node->valuestring);
		if(strncmp(node->valuestring,"res",3) == 0){
			node = cJSON_GetObjectItem(json,"res");
			if(node == NULL){
				printf("error:cJSON_GetObjectItem\n");
				cJSON_Delete(json);
				exit(-1);
			}

			if(node->type == cJSON_Number){
				printf("res:%.2f\n",node->valuedouble);
			}
		}
	}else{
		printf("%s\n",node->valuestring);
	}
	cJSON_Delete(json);
}

